// 提醒时间纠正
var mongoose = require('mongoose');
var moment = require('moment');
var _ = require('underscore');
var async = require("async");
var CustomRemind = mongoose.model('CustomRemind');
var Schedule = mongoose.model('Schedule');
var constant = require("../conf/config").constant;
var scheduleDate = require('../util/scheduleDate');
var period = constant.period;

module.exports = function() {

    var format = 'YYYY-MM-DD HH:MM:ss';
    var scheduleCount = 0;
    var size = 1000;

    var start  = function() {
        scheduleCount = 0;
        Schedule.count({deadline : {$gt : new Date()}, repeat : {$ne : period.NONE}}, function(err, count){
            if (err) {
                console.error('获取不重复日程总数异常：%s', JSON.stringify(err));
            } else {
                scheduleCount = count;
                queryScheduled();
            }
        });
    };

    var queryScheduled = function() {
        var condition = {deadline : {$gt : new Date()}, repeat : {$ne : period.NONE}};

        for (var currPoint = 0; currPoint < scheduleCount; currPoint += size) {
            // 查询出所有复重的日程，且截止时间大于当前时间
            Schedule.find(condition).skip(currPoint).limit(size).exec(function(err, schedules){
                if (err) {
                    console.error('分页查询所有重复日程数据出错，start:%s, size: %s, error: %s', currPoint, size, JSON.stringify(err));
                } else {
                    queryReminds(schedules);
                }
            });
        }
    };

    var queryReminds = function(schedules){
        async.each(schedules, function(schedule){
            CustomRemind.find({scheduleId : schedule._id}, function(err, reminds) {
                _.each(reminds, function(remind){
                    correctionRemind(schedule, remind);
                });
            });
        });
    };

    var correctionRemind = function(schedule, remind){
        var date = schedule.type == constant.scheduleType.MEETING ? schedule.timeScope.start : schedule.timeScope.end;
        var nextDate = scheduleDate.recalculateNextRemindTime(date, remind.leadMinute, remind.repeat);
        var diff = moment(remind.alarm).diff(moment(), 'minute');
        // 当数据中的执行时间与当前执行时间前后五分钟的时差数据不做处理, 怕与提醒冲突所以允许这样的误差
        // 当算出新的时间与原有时间没有超过一分钟误差时也不做处理，充许这样偏差存在
        if ((diff > -5 && diff < 5) || moment(remind.alarm).isSame(nextDate, 'minute')) {
            return;
        }

        console.info('日程id【%s】，人员id为【%s】的下一次提醒时间不对，原时间为%s，纠正为：%s',
            remind.scheduleId,  remind.memberId,  moment(remind.alarm).format(format),
            moment(nextDate).format(format));

        CustomRemind.update({_id: remind._id},
            {$set : {alarm : nextDate, lastModifyTime : new Date()}, $inc: { __v: 1 }},
            function(err, num){
                if (err) {
                    console.error('纠正修改提醒数据【%s】异常:%s', JSON.stringify(remind), JSON.stringify(err));
                }
         });
    };


    return {
        start   :   start
    }
}();